#include "CubemapTexture.h"
#include <iostream>
using namespace std;


static const GLenum types[6] = {  GL_TEXTURE_CUBE_MAP_POSITIVE_X,
                                  GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
                                  GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
                                  GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
                                  GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
                                  GL_TEXTURE_CUBE_MAP_NEGATIVE_Z };

CubemapTexture::CubemapTexture(const string Directory,
                   const string PosXFilename,
                   const string NegXFilename,
                   const string PosYFilename,
                   const string NegYFilename,
                   const string PosZFilename,
                   const string NegZFilename)
{
    string::const_iterator it = Directory.end();
    it--;
    string BaseDir = (*it == '/') ? Directory : Directory + "/";
    
	//	Filepath + File
    m_fileNames[0] = BaseDir + PosXFilename;
    m_fileNames[1] = BaseDir + NegXFilename;
    m_fileNames[2] = BaseDir + PosYFilename;
    m_fileNames[3] = BaseDir + NegYFilename;
    m_fileNames[4] = BaseDir + PosZFilename;
    m_fileNames[5] = BaseDir + NegZFilename;
    
    m_textureObj = 0;
}


CubemapTexture::~CubemapTexture(void)
{
	 if (m_textureObj != 0) 
	 {
        glDeleteTextures(1, &m_textureObj);
     }
}

bool CubemapTexture::Load()
{
	// Create one OpenGL texture
	//GLuint textureID;
	glGenTextures(1, &m_textureObj);

	// "Bind" the newly created texture : all future texture functions will modify this texture
	glBindTexture(GL_TEXTURE_CUBE_MAP, m_textureObj);
					
	for (int i = 0; i < 6; i++)
	{
		m_textures[i] = new TextureImage();

		if(!m_textures[i]->loadBMP(m_fileNames[i].c_str()))
		{
			std::cout << "loading BMP in Cubemap failed" << std::endl;
			if (std::cin.get() == '\n')		
				return false;
		}
		
		glTexImage2D(types[i], 0, GL_BGR, m_textures[i]->getWidth(), m_textures[i]->getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, m_textures[i]->getData());
		//glTexImage2D(types[i], 0, GL_BGR, m_textures[i].getWidth(), m_textures[i].getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, 0);
	}
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);           

	return true;
}

void CubemapTexture::Bind(GLenum TextureUnit)
{
    glActiveTexture(TextureUnit);
    glBindTexture(GL_TEXTURE_CUBE_MAP, m_textureObj);
}

